/**
 * @desc 用户列表组件
 * */
import React from "react";
import { connect } from "react-redux";
import { Space, Tag, Button } from "antd";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import SearchForm from "./component/searchForm";
import UserAdd from "./component/add";
import UserUpdate from "./component/update";
import { apiUserPage, apiUserDel, apiUserState, apiRoleList } from "@/request/system/user";


class Users extends React.Component {
    //定义表单ref
    state = {
        dataSource: [],
        dialogType: "add",
        title: "新增",
        detailId: null,
        loading: false,
        dialogStatus: false,
        totalPage: 1,//当前页数
        total: 1,//分页总数
        pageParams: {
            pageNo: 1,
            pageSize: 10
        },
        roleList: [],
        searchParams: {},
        columns: [
            {
                title: '序号',
                align: 'center',
                width: 80,
                render: (text, record, index) => {
                    return (
                        //当前页数减1乘以每一页页数再加当前页序号+1
                        `${(this.state.pageParams.pageNo - 1) * (this.state.pageParams.pageSize) + (index + 1)}`
                    )
                }
            },
            {
                title: '用户名',
                dataIndex: 'loginName',
                align: 'center'
            },
            {
                title: "姓名",
                align: 'center',
                dataIndex: "userName"
            },
            {
                title: "手机号",
                align: 'center',
                dataIndex: "userMobile"
            },
            {
                title: "角色",
                align: 'center',
                dataIndex: "roleNames",
                render: text => <div style={{
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    width: 200
                }}>{text === 'STORE' ? '门店管理员' : text}</div>,
                width: 200
            },
            {
                title: "创建时间",
                align: 'center',
                dataIndex: "createTime"
            },
            {
                title: "创建人",
                align: 'center',
                dataIndex: "createUserName"
            },
            {
                title: "状态",
                align: 'center',
                render: (text, record) => (
                    <>
                        {record.status === 'Y' && <Tag color="green">正常</Tag>}
                        {record.status === 'N' && <Tag color="red">冻结</Tag>}
                    </>
                )
            },
            {
                title: "操作",
                key: "name",
                width: 220,
                render: (text, record) => (
                    <Space size="small">
                        {
                            record.loginName !== 'admin' && record.status === 'Y' &&
                            <TheButton  type="link" size='small' hasPermi={['settings:user:freezon']}
                                onClick={() => this.freeze('N', record)}>冻结</TheButton>
                        }
                        {
                            record.loginName !== 'admin' && record.status === 'N' &&
                            <TheButton type="link" size='small' hasPermi={['settings:user:freezon']}
                                onClick={() => this.freeze('Y', record)}>解冻</TheButton>
                        }
                        {record.loginName !== 'admin' && <TheButton hasPermi={['settings:user:edit']} type="link" size='small' auth={'user:update'}
                            onClick={() => this.update(record)}>编辑</TheButton>}
                        {record.loginName !== 'admin' && <TheButton type="link" hasPermi={['settings:user:delete']} size='small' auth={'user:delete'}
                            onClick={() => this.del(record.userId)}>删除</TheButton>}
                    </Space>
                ),
                fixed: 'right'
            }
        ]
    };

    componentDidMount() {
        this.getList();
        this.getRoleList()
    }

    /**
     * @desc 新增用户
     * */
    add = () => {
        this.setState({
            dialogStatus: true,
            dialogType: 'add',
            title: '新增用户'
        })
    }
    /**
     * @desc 修改用户
     * */
    update = (data) => {
        this.setState({
            detailId: data.userId,
            dialogStatus: true,
            dialogType: 'update',
            title: '修改用户'
        })
    }
    /**
     * @desc 获取角色列表
     * */
    getRoleList = async () => {
        const res = await apiRoleList({ pageNo: 1, pageSize: 1000, status: 'Y' });
        if (res.code === 0 && res.data) {
            this.setState({
                roleList: res.data.map(v => {
                    return {
                        label: v.roleName === 'STORE' ? '门店管理员' : v.roleName,
                        value: v.storeRoleId,
                        disabled: v.roleEnglishName === 'SUPERADMIN'
                    }
                })
            })
        }
    }
    /**
     * @desc 获取表格数据
     * */
    getList = async (params = this.state.pageParams) => {
        this.setState({ loading: true })
        const data = await apiUserPage(params)
        if (data.code === 0) {
            this.setState({
                dataSource: data.data,
                total: data.totalCount,
                totalPage: data.totalPage,
                pageParams: {
                    pageNo: data.pageNo,
                    pageSize: data.pageSize
                }
            })
        }
        this.setState({ loading: false })
    }
    /**
     * @desc 冻结
     * */
    freeze = (status, data) => {
        const that = this;
        React.$confirm({
            title: "警告",
            content: "确定要冻结吗？",
            async onOk() {
                const res = await apiUserState({ userId: data.userId, status: status })
                if (res.code === 0) {
                    React.$message({
                        type: "success",
                        content: "冻结成功"
                    });
                    await that.getList();
                }
            }
        });
    }
    /**
     * @desc 删除事件
     * */
    del = (userId) => {
        const that = this;
        React.$confirm({
            title: "警告",
            content: "确定要删除吗？",
            async onOk() {
                const res = await apiUserDel({ userId })
                if (res.code === 0) {
                    React.$message({
                        type: "success",
                        content: "删除成功"
                    });
                    await that.getList()
                }
            }
        });
    };
    /**
     * @desc 分页事件
     * */
    pageChange = async (pageNo, pageSize) => {
        console.log(pageNo);
        const searchParams = this.state.searchParams;
        const param = Object.assign({
            pageNo,
            pageSize
        }, searchParams)
        await this.getList(param)
    };
    /**
     * @desc 弹窗关闭事件
     * */
    dialogClose = () => {
        this.setState({ dialogStatus: false });
    };

    render() {
        const {
            dataSource,
            columns,
            loading,
            dialogStatus,
            title,
            dialogType,
            total,
            detailId,
            pageParams,
            roleList
        } = this.state;
        return (
            <div className={"p-layout-box"}>
                {/*顶部搜索区域*/}
                <div className={"p-search-box"}>
                    <SearchForm onFinish={this.search} ref={(ref) => {
                        this.searchRef = ref;
                    }} add={this.add} />
                </div>
                {/*表格区域*/}
                <div className={"p-layout-content-pagination"}>
                    <TheTable rowKey={"userId"} loading={loading} dataSource={dataSource} columns={columns} />
                    <ThePagination total={total} pageNo={pageParams.pageNo} pageSize={pageParams.pageSize}
                        pageChange={this.pageChange} />
                </div>
                {/*增删改查弹窗*/}
                <TheDialog
                    visible={dialogStatus}
                    title={title}
                    handleCancel={this.dialogClose}
                    footer={null}
                >
                    {
                        /* 新增弹窗*/
                        dialogType === 'add' &&
                        <UserAdd handleCancel={this.dialogClose} roleList={roleList} getList={this.getList}
                            handleOk={this.dialogSave} />
                    }
                    {
                        /* 编辑弹窗*/
                        dialogType === 'update' &&
                        <UserUpdate id={detailId} handleCancel={this.dialogClose} roleList={roleList}
                            getList={this.getList}
                            handleOk={this.dialogSave} />
                    }
                </TheDialog>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        user: state.user
    };
};
export default connect(mapStateToProps, null)(Users);
